define(function(require, exports, module) {
    "use strict";
    var $ = require("$"),
        app = require("dist/application/app"),
        config = app.config,
        _ = require("underscore");
    var tips = require("dist/tips/init");

    var data = require("./data");
    var box_tmp = require("./template/area_box.html");
    var cities_tmp = require("./template/area_cities.html");
    var areas_tmp =  require("./template/areas_tmp.html");
    var js_node_tmp = require("./template/js_node_box.html");

	var LeveLinkage = function(options) {
		this.opts = $.extend(true,{},options||{});
        this.currProvince = "110000";
        this.codeProvince = "110100";
        this.element = null;
        this.name = null;
        this.text= null;
        this.selectCities = [];
        this.selectAreas = {};
        this.selectedMap = {};
        this.selectedData = {};
        this.selectAreaName = "北京市";

        this.init();
        this.selectProvinceyInit();
        
    }

    LeveLinkage.prototype.init = function(){
    	this.data = data;
    	var _this = this;

    	$(document).on("click", ".js_edit_city", function(e) {
	        var $this = $(this),
	            $area_item = $this.nextAll("span.js_area_item");
	            _this.element = $area_item;
	            _this.name = $this.data("name");
	            _this.text = $this.data("text");
	            _this.currProvince = "110000";
        		_this.codeProvince = "110100";
            if (_this.element) {
	            var attr = $('input[type="hidden"]', _this.element).val();
	            if (attr) {
	                _this.selectedMap = window.JSON.parse(attr)
	            };
	        }

	        var dialog = tips.msgbox.dialog({
	            message: _this.html(),
	            title: "选择可配送区域",
	            buttons: {
	                success: {
	                    label: "确定",
	                    className: "btn-primary",
	                    callback: function() {
	                        _this.success()
	                    }
	                },
	                cancel: {
	                    label: "取消"
	                }
	            }
	        });
	        dialog.on("shown.bs.modal", function() {
	        	_this.selectProvinceyInit();
	            _this.currentPlace();
	        }); 
	    });

    	$(document).on("change", "select.js_province_cxselect", function() {
            _this.currProvince = $(this).val();
            _this.currentPlace();
            _this.changeCities();
        })

        $(document).on("click", "a.js_show_area", function(e) {
        	e && e.stopPropagation();
        	if($(this).hasClass("active")) return;
        	$(this).addClass("active");
        	$(this).closest("li").siblings("li").find("a.js_show_area").removeClass("active");
            _this.codeProvince = $(this).data("id");
            _this.selectAreaName = $(this).data("name");
            _this.currentPlace()
            _this.changeAreas();
        })

        //城市全选
        $(document).on("click", "input.js_citys_checkall", function(e) {
        	e && e.stopPropagation();
            var $this = $(e.target),
                checked = $this.is(':checked');
            var checkitems = $("input.js_citys_checkitem", $("ul.js_cities_cxselect"));
            checkitems.prop('checked', checked);
            checkitems.trigger("select");
            _this.checkAll(checked,_this.currProvince,$("ul.js_cities_cxselect"));
        })
        $(document).on("click", "input.js_citys_checkitem", function(e) {
            e && e.stopPropagation();
            _this.codeProvince = $(this).data("id");
            _this.selectProvinceyInit();
            _this.selectCity(this);
        })
        $(document).bind("select", "input.js_citys_checkitem", function(e) {
            e && e.stopPropagation();
            _this.codeProvince = $(e.target).data("id");
            _this.selectProvinceyInit();
            _this.selectCity(e.target);
        });


        //区域全选 js_areas_cxselect
        $(document).on("click", "input.js_areas_checkall", function(e) {
            var $this = $(e.target),
                checked = $this.is(':checked');
            var checkitems = $("input.js_areas_checkitem", $("ul.js_areas_cxselect"));
            checkitems.prop('checked', checked);
            checkitems.trigger("selected");
            _this.checkAll(checked,_this.codeProvince,$("ul.js_areas_cxselect"));
        })

        $(document).on("click", "input.js_areas_checkitem", function(e) {
            e && e.stopPropagation();
            _this.selectArea(this);
        })
        $(document).bind("selected", "input.js_areas_checkitem", function(e) {
            e && e.stopPropagation();
            _this.selectArea(e.target);
        });


        //选中城市展开收缩
        $(document).on("click","a.js-tree-expand",function(){
        	$(this).toggleClass("tree-expand-close");
        	if($(this).hasClass("tree-expand-close")){
        		$(this).closest("div.nodes-item").next("div.nodes-items").addClass("hide");
        	}else{
        		$(this).closest("div.nodes-item").next("div.nodes-items").removeClass("hide");
        	}
        })

    };


    //转换选中数据  生成选中省市区html
    LeveLinkage.prototype.showSelectedCitiesInit = function() {
        var data = [],parr = [],last;this.selectedData = {};
        for (var pid in this.selectedMap) {
        	var p = this.selectedMap[pid];
        	var pd = this.data[0][pid];

        	for (var c in p) {
                var item = p[c];
                if (item instanceof Object) {
                	if(this.selectedMap[item.id]){
                		var count = Object.keys(this.selectedMap[item.id]).length - 1;

                		for(var s in this.selectedMap[item.id]){
                			var list = this.selectedMap[item.id][s];
                			
                			if (list instanceof Object) {
                				last = list.id;
                			}
                		}
                		
            			data.push({
                			id:item.id,
                			name:item.name,
                			arears:this.selectedMap[item.id],
                			last:last,
                			count:count,
                			pid:pid,
                			pname:pd
                		})
                	}
                }
            }
        }
        

        this.selectedData =  _.groupBy(data,function(n){ return n.pid} );

        for (var key in this.selectedData) {
        	var k = this.selectedData[key];
        	var carr = [];
        	for(var c in k){
        		var item = k[c];
        		if (item instanceof Object) {
                    carr.push(k[c].name);
                }

                var s = k[c].arears;
                var sarr = [];
                
                	
            	if(s["checkall"] && s["checkall"] == true){
            		sarr.push(item.name)
            	}else{
                	for(var i in s){
            			var areasItem = s[i];
            			if(areasItem instanceof Object){
	                		sarr.push(s[i].name);
	                	}
            		}
            	}

            	if(sarr.length >= 1){
            		carr.push("({0})".format(sarr.join("、")));
            	}
        	}
        	if(carr.length > 0){
        		parr.push("{0} [{1}]".format(k[0].pname,carr.join("、")))
        	}
        }

        $("div.js_select_html").html(this.showSelectedTree());
        return parr.join(",");
    };


    LeveLinkage.prototype.html = function() {
        var render = template.compile(box_tmp),_this = this;
        return render({
            provinces: this.data[0],
            cities_html: this.citiesHtml(),
            areas_html: this.areasHtml(),
            select_html:this.showSelectedTree()
        });
    };

    LeveLinkage.prototype.citiesHtml = function() {
    	var index = "0,"+this.currProvince;
        var data = this.data[index];
        var render = template.compile(cities_tmp);
        var map = {};
        for (var c in data) {   
        	map[c] = {
        		id :c,
	        	name : data[c],
	        	checked : (this.checkSelectedCity(c,this.currProvince) ? 'checked="checked"' : '')
        	}  	
        }

        this.selectCities = map;
        var count = Object.keys(this.selectCities).length;
        return render({
            data: map,
            checkAllShow: count > 1,
            checkAll: this.selectedMap[this.currProvince]["checkall"] ? 'checked="checked"' : '',
            currProvince: this.currProvince
        });

    };

    LeveLinkage.prototype.areasHtml = function() {
    	var index = "0,"+this.currProvince+","+this.codeProvince;
        var data = this.data[index];
        var render = template.compile(areas_tmp);
        var map = {};
        for(var c in data){
        	map[c] = {
        		id:c,
        		name:data[c],
        		checked: (this.checkSelectedCity(c,this.codeProvince) ? 'checked="checked"' : '')
        	}
        }
        this.selectAreas = map;
        var count = Object.keys(this.selectAreas).length;

        return render({
            data: map,
            checkAllShow: count > 1,
            checkAll: this.selectedMap[this.codeProvince]["checkall"] ? 'checked="checked"' : '',
            codeProvince: this.codeProvince,
            name:this.selectAreaName
        });
    };

    //生成选中省市区html---之前没定义好 搞得又重写这个方法  没写好
    LeveLinkage.prototype.showSelectedTree = function() { 
    	var data = [],parr = [],last,selectedData = {};
    	
        for (var pid in this.selectedMap) {
        	var p = this.selectedMap[pid];
        	var pd = this.data[0][pid];

        	for (var c in p) {
                var item = p[c];
                if (item instanceof Object) {
                	if(this.selectedMap[item.id]){
                		var count = Object.keys(this.selectedMap[item.id]).length - 1;
                		for(var s in this.selectedMap[item.id]){
                			var list = this.selectedMap[item.id][s];
                			if (list instanceof Object) {
                				last = list.id;
                			}
                		}
            			data.push({
                			id:item.id,
                			name:item.name,
                			arears:this.selectedMap[item.id],
                			last:last,
                			count:count,
                			pid:pid,
                			pname:pd
                		})
                	}
                }
            }
        }
        
        selectedData =  _.groupBy(data,function(n){ return n.pid} );


		var render = template.compile(js_node_tmp);
    	var datas = [];

    	/*if(Object.keys(this.selectedMap[this.codeProvince]).length <= 1){
        	selectedData = {};
        }*/

    	for(var i in selectedData){
    		datas.push(selectedData[i])
    	}

    	return render({
    		data:datas
    	})
    };

    //改变市
    LeveLinkage.prototype.changeCities = function(){
    	this.selectProvinceyInit();
    	$("ul.js_cities_cxselect").html(this.citiesHtml());
    	$("ul.js_areas_cxselect").empty();
    }

    //改变区
    LeveLinkage.prototype.changeAreas = function(){
    	this.changeCities()
    	$("ul.js_areas_cxselect").html(this.areasHtml());
    }


    //返回是否选中状态
    LeveLinkage.prototype.checkSelectedCity = function(city,code) {
        var p = this.selectedMap[code];
        if (p["checkall"] && p["checkall"] == true) {
            return true;
        } else {
            return p[city] != undefined;
        }
    }

    //当前位置
    LeveLinkage.prototype.currentPlace = function(){

    	var $place = $("span.current_place",".select_org_lists");
    	var curr = this.currProvince,$index = "0,"+this.currProvince;
     	var $currHtml = this.data[0][curr];
     	var $cityHtml = this.data[$index][this.codeProvince] ? ":"+this.data[$index][this.codeProvince] : config.empty;
       	$place.html($currHtml+$cityHtml);

    }

    LeveLinkage.prototype.selectCity = function(target) {
        var $this = $(target),
            city = $this.data();
        var checked = $this.prop('checked');
        
        var p = this.selectedMap[this.currProvince];
        var index = "0,"+this.currProvince;

        if (checked) {
            var selectCities = this.selectCities;
            p[city.id] = selectCities[city.id];
            if (this.checkCityEl().length == Object.keys(selectCities).length) {
                this.checkAll(true,this.currProvince,$("ul.js_cities_cxselect"));
            };
        } else {
	    	if(this.verifyIsAre(this.selectedMap[this.codeProvince])) return;
            this.checkAll(false,this.currProvince,$("ul.js_cities_cxselect"));
            delete this.selectedMap[this.currProvince][city.id];
        }
        
        this.showSelectedCitiesInit();
    };

    LeveLinkage.prototype.selectArea = function(target) {
        var $this = $(target),
            city = $this.data();
        var checked = $this.prop('checked');

        var p = this.selectedMap[this.codeProvince];

        var city_s = this.selectedMap[this.currProvince];

        var index = "0,"+this.currProvince+","+this.codeProvince;

		if(!this.verifyIsAre(city_s)){
    		city_s[this.codeProvince] = {
				id:this.codeProvince,
				name:this.selectAreaName
			}
    	}

        if (checked) {
            var selectAreas = this.selectAreas;
            p[city.id] = selectAreas[city.id];

            if (this.checkAreaEl().length == Object.keys(selectAreas).length) {
                this.checkAll(true,this.codeProvince,$("ul.js_areas_cxselect"));
            };

        } else {
    		if(_.indexOf(_.keys(this.selectedMap[this.currProvince][this.codeProvince]),"checked") <= -1){
    			delete this.selectedMap[this.currProvince][this.codeProvince];
    		}
            this.checkAll(false,this.codeProvince,$("ul.js_areas_cxselect"));
            delete this.selectedMap[this.codeProvince][city.id];

        }
        
        this.showSelectedCitiesInit();
    };

    LeveLinkage.prototype.selectProvinceyInit = function() {
        if (!this.selectedMap[this.currProvince]) {
            this.selectedMap[this.currProvince] = {};
            this.selectedMap[this.currProvince]["checkall"] = false;
        };

        if (!this.selectedMap[this.codeProvince]) {
            this.selectedMap[this.codeProvince] = {};
            this.selectedMap[this.codeProvince]["checkall"] = false;
        };
    };

    LeveLinkage.prototype.verifyIsAre = function(city_s){
    	for(var k in city_s){
			var item = city_s[k];
			var flog = (item instanceof Object);
			return flog;
		}
    }

    //没保存就清空
    LeveLinkage.prototype.clean = function(element){
    	if (element) {
            var attr = $('input[type="hidden"]', element).val();
            if (attr) {
                this.selectedMap = window.JSON.parse(attr)
            };
        }
    }
    
    LeveLinkage.prototype.checkAll = function(checked,$thisCurrProvince,js_cities) {
        $("input.js_citys_checkall",js_cities).prop('checked', checked);
        $("input.js_areas_checkall",js_cities).prop('checked', checked);
        this.selectedMap[$thisCurrProvince]["checkall"] = checked;
    };

    LeveLinkage.prototype.checkCityEl = function() {
        return $("input.js_citys_checkitem:checked", $("ul.js_cities_cxselect"));
    };

    LeveLinkage.prototype.checkAreaEl = function() {
        return $("input.js_areas_checkitem:checked", $("ul.js_areas_cxselect"));
    };

    LeveLinkage.prototype.success = function(){
    	var showHtml = this.showSelectedCitiesInit();
        var msg=this.element.data("msg") || "请选择可配送区域",classes=this.element.data("classes") || "";
        this.element.html(showHtml.length > 1 ? showHtml : "<span class='js_no_area "+classes+"'>"+msg+" </span>");
        this.element.append("<input type='hidden' name='{0}'  value='{1}'>".format(this.name, window.JSON.stringify(this.selectedMap)));
        this.element.append("<input type='hidden' name='{0}'  value='{1}'>".format(this.text,showHtml));
        this.currProvince = "110000";
        this.codeProvince = "110100";
    }

	return LeveLinkage;
})